﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Security.Application;
using AGR.Services.Course;
using AGR.Services.Course.Contract;
using AGR.Model;
using AGR.Services;

namespace AGR.Web.Pages.Courses
{
    public partial class Courses : System.Web.UI.Page
    {
        private ICourseService _courseService = new CourseService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ClearMessage();
                this.LoadGrid();
            }
        }

        #region Button Methods

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchBy = txtSearch.Text;

            if (string.IsNullOrEmpty(searchBy))
            {
                this.ShowMessage("Please enter a search parameter and try again.", SiteMaster.MessageType.Information);
                txtSearch.Focus();
                return;
            }

            this.ClearMessage();

            var result = _courseService.GetAllCourses(x => x.CourseCode == searchBy ||
                                                           x.CourseName.Contains(searchBy) ||
                                                           x.AccreditationNumber == searchBy ||
                                                           x.Category.Contains(searchBy) ||
                                                           x.CertificateType.Contains(searchBy));

            this.LoadGrid(result);
        }

        protected void btnSearchClear_Click(object sender, EventArgs e)
        {
            this.ClearMessage();
            txtSearch.Text = string.Empty;
            this.LoadGrid();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            CourseGridView.ShowFooter = true;
            CourseGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool selected = false;
            int selectCount = 0;
            int deleteCount = 0;
            string succesMessages = string.Empty;
            string errorMessages = string.Empty;

            IList<ActionResult> results = new List<ActionResult>();

            for (int i = 0; i < CourseGridView.Rows.Count; i++)
            {
                var row = CourseGridView.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

                if (isChecked)
                {
                    // TODO: Check relationships before delete

                    string code = (string)this.CourseGridView.DataKeys[i].Value;
                    results.Add(_courseService.DeleteCourse(code));
                    selected = true;
                    selectCount++;
                }
            }

            if (selected == false)
            {
                this.ShowMessage("Please select records for deletion and try again.", SiteMaster.MessageType.Information);
                return;
            }

            foreach (ActionResult result in results)
            {
                if (result.Success)
                {
                    succesMessages = result.Message;
                    deleteCount++;
                }
                else
                    errorMessages = result.Message;
            }

            if (!string.IsNullOrEmpty(succesMessages))
                this.ShowMessage(succesMessages, SiteMaster.MessageType.Success);

            if (!string.IsNullOrEmpty(errorMessages))
                this.ShowMessage(errorMessages + " " + (selectCount - deleteCount) + " record(s) was not deleted.", SiteMaster.MessageType.Error);

            CourseGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void btnCourseDetailsClose_Click(object sender, EventArgs e)
        {
            ucCourseDetail.ClearDetail();
            CourseDetailModalPopupExtender.Hide();
        }
        
        #endregion

        #region GridView Methods

        protected void CourseGridView_OnRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                string courseCode = ((TextBox)CourseGridView.FooterRow.FindControl("txtCourseCode")).Text.ToString();

                var exists = _courseService.GetCourse(courseCode);

                if (exists != null)
                {
                    this.ShowMessage("Your action could not be completed. A record with course code (" + courseCode + ") already exists on the system.", SiteMaster.MessageType.Warning);
                    return;
                }

                var entity = new Course
                {
                    CourseCode = courseCode,
                    CourseName = ((TextBox)CourseGridView.FooterRow.FindControl("txtCourseName")).Text.ToString(),
                    AccreditationNumber = ((TextBox)CourseGridView.FooterRow.FindControl("txtAccreditationNumber")).Text.ToString(),
                    Category = ((TextBox)CourseGridView.FooterRow.FindControl("txtCategory")).Text.ToString(),
                    CertificateType = ((TextBox)CourseGridView.FooterRow.FindControl("txtCertificateType")).Text.ToString(),
                    UserCreated = "TestUser"
                };

                var result = _courseService.AddCourse(entity);

                if (result.Success)
                {
                    this.ShowMessage(result.Message, SiteMaster.MessageType.Success);
                    CourseGridView.ShowFooter = false;
                    CourseGridView.EditIndex = -1;
                    this.LoadGrid();
                }
                else
                    this.ShowMessage(result.Message, SiteMaster.MessageType.Error);
                
            }
            else if (e.CommandName == "CancelInsert")
            {
                this.ClearMessage();
                CourseGridView.ShowFooter = false;
                CourseGridView.EditIndex = -1;
                this.LoadGrid();
            }
        }

        protected void CourseGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            this.ClearMessage();
            string primaryKey = CourseGridView.DataKeys[e.NewSelectedIndex].Value.ToString();
            ucCourseDetail.LoadDetail(primaryKey);
            CourseDetailModalPopupExtender.Show();
        }

        protected void CourseGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string courseCode = ((TextBox)CourseGridView.Rows[e.RowIndex].FindControl("txtCourseCode")).Text.ToString();

            var entity = _courseService.GetCourse(x => x.CourseCode == courseCode);

            entity.CourseCode = courseCode;
            entity.CourseName = ((TextBox)CourseGridView.Rows[e.RowIndex].FindControl("txtCourseName")).Text.ToString();
            entity.AccreditationNumber = ((TextBox)CourseGridView.Rows[e.RowIndex].FindControl("txtAccreditationNumber")).Text.ToString();
            entity.Category = ((TextBox)CourseGridView.Rows[e.RowIndex].FindControl("txtCategory")).Text.ToString();
            entity.CertificateType = ((TextBox)CourseGridView.Rows[e.RowIndex].FindControl("txtCertificateType")).Text.ToString();
            entity.UserModified = "TestUser";

            var result = _courseService.UpdateCourse(entity);

            if (result.Success)
            {
                this.ShowMessage(result.Message, SiteMaster.MessageType.Success);
                CourseGridView.EditIndex = -1;
                this.LoadGrid();
            }
            else
                this.ShowMessage(result.Message, SiteMaster.MessageType.Error);
        }

        protected void CourseGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.ClearMessage();
            CourseGridView.ShowFooter = false;
            CourseGridView.EditIndex = e.NewEditIndex;
            this.LoadGrid();
        }

        protected void CourseGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            CourseGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void CourseGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            CourseGridView.PageIndex = e.NewPageIndex;
            CourseGridView.EditIndex = -1;

            this.LoadGrid();
        }

        #endregion

        #region Private Methods

        private void LoadGrid()
        {
            var courses = _courseService.GetAllCourses();

            if (courses.Count == 0)
            {
                courses.Add(new Course());
                CourseGridView.ShowFooter = true;
                CourseGridView.EditIndex = -1;

                CourseGridView.DataSource = courses;
                CourseGridView.DataBind();
                CourseGridView.Rows[0].Visible = false;
            }
            else
            {
                CourseGridView.DataSource = courses;
                CourseGridView.DataBind();
            }
        }

        private void LoadGrid(IList<Course> courses)
        {
            CourseGridView.DataSource = courses;
            CourseGridView.DataBind();
        }

        private void ShowMessage(string message, AGR.Web.SiteMaster.MessageType messagetype)
        {
            var master = (SiteMaster)Page.Master;
            master.ShowMessage(message, messagetype);
        }

        private void ClearMessage()
        {
            var master = (SiteMaster)Page.Master;
            master.ClearMessage();
        }

        #endregion
    }
}